package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    private RestHighLevelClient restHighLevelClient;
    /**
     * 上架商品到es ***
     * @return
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {
        //保存到es
        //1、给es中建立索引。product，建立好映射关系。
        BulkRequest bulkRequest = new BulkRequest();
        //2、给es中保存这些数据
        //BulkRequest bulkRequest, RequestOptions options
        for(SkuEsModel model:skuEsModelList){
            //bulkRequest.add(new IndexRequest("product").id(skuEsModel.getSkuId().toString()).source(JSONUtil.toJsonStr(skuEsModel)));
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            //indexRequest.source();
            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        List<Integer> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getItemId();
        }).collect(Collectors.toList());
//        log.error("商品上架出错：{}",collect);
        log.info("商品上架完成：{},返回数据:{}",collect,bulk.toString());
        return b;
    }
}
